<template>
  <div>
    <el-card style="height: 80px">
      <el-form inline class="searchForm">
        <el-form-item label="用户名:"
          ><el-input v-model="keyword" placeholder="用户名关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            @click="searchUser"
            :disabled="!keyword"
            >搜索</el-button
          >
          <el-button
            type="default"
            size="default"
            @click="settingStore.refsh = !settingStore.refsh"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-button
        size="default"
        icon="Plus"
        type="primary"
        @click="addUser"
        v-has="'btn.User.add'"
        >添加用户</el-button
      >
      <el-button
        :disabled="!(userSelecedArr.length > 0)"
        size="default"
        icon="Delete"
        type="danger"
        @click="deleteUserArr"
        v-has="'btn.User.remove'"
        >批量删除</el-button
      >
      <el-table
        border
        :data="userList"
        style="margin-top: 10px"
        @selection-change="handleSelectionChange"
        v-loading="tableLoading"
      >
        <el-table-column
          align="center"
          type="selection"
          width="60"
        ></el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
        ></el-table-column>
        <el-table-column align="center" label="ID" prop="id"></el-table-column>
        <el-table-column
          align="center"
          label="用户名"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="昵称"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #="{ row }">
            <el-button
              size="small"
              icon="User"
              type="primary"
              @click="updateUserRole(row)"
              >分配角色</el-button
            >
            <el-button
              size="small"
              icon="Edit"
              type="warning"
              @click="updateUser(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`确定删除${row.username}吗?`"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button
                  size="small"
                  icon="Delete"
                  type="danger"
                  v-has="'btn.User.remove'"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="pageSize"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="getUserList"
        @current-change="getUserList"
      />
    </el-card>
    <!-- 添加用户抽屉 -->
    <el-drawer
      v-model="addUserDrawer"
      :title="newUserData.id ? '编辑管理用户' : '添加管理用户'"
      direction="rtl"
    >
      <el-form
        :model="newUserData"
        label-width="100"
        :rules="newUserDataRule"
        ref="newUserDataForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="newUserData.username"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            v-model="newUserData.name"
            placeholder="请输入昵称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model="newUserData.password"
            placeholder="密码"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="default" size="default" @click="addUserDrawer = false"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="submitAddUser"
          >提交</el-button
        >
      </template>
    </el-drawer>
    <!-- 分配角色抽屉 -->
    <el-drawer v-model="userRoleDrawer" title="分配用户角色" direction="rtl">
      <el-form label-width="100">
        <el-form-item label="用户名">
          <el-input
            v-model="newUserData.username"
            placeholder="请输入用户名"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox v-for="i in allRole" :key="i.id" :label="i">{{
              i.roleName
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="default" size="default" @click="userRoleDrawer = false"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="submitUserRole"
          >提交</el-button
        >
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import * as userRequest from "@/api/acl/user";
import { userResponseData, userObj } from "@/api/acl/user/type";
import checkResult from "@/utils/notice";
// 引入框架仓库，用于点击重置按钮刷新
import useLayoutSettingStore from "@/store/modules/setting";
let settingStore = useLayoutSettingStore();

let pageNo = ref<number>(1);
let limit = ref<number>(3);
let pageSize = ref<number[]>([3, 5, 7, 10]);
let total = ref<number>(0);
let userList = ref<userObj[]>([]);
let addUserDrawer = ref<boolean>(false);
let userSelecedArr = ref<userObj[]>([]);
let tableLoading = ref<boolean>(false);

//收集要添加用户的数据
let newUserDataForm = ref();
let newUserData = reactive<userObj>({
  name: "",
  password: "",
  username: "",
});
let newUserDataRule = reactive<any>({
  name: [
    { required: true, message: "必须输入昵称", trigger: "blur" },
    { min: 6, message: "长度必须大于6", trigger: "blur" },
  ],
  password: [
    { required: true, message: "必须输入密码", trigger: "blur" },
    { min: 6, message: "长度必须大于6", trigger: "blur" },
  ],
  username: [
    { required: true, message: "必须输入用户名", trigger: "blur" },
    { min: 6, message: "长度必须大于6", trigger: "blur" },
  ],
});

//用户角色相关
let userRoleDrawer = ref<boolean>(false);
let allRole = ref<any[]>([]);
let userRole = ref<any[]>([]);
let checkAll = ref<boolean>(false);
let isIndeterminate = ref<boolean>(false);

//搜索相关
let keyword = ref<string>("");
const searchUser = () => {
  getUserList(1, keyword.value);
};

//获取所有用户列表
const getUserList = async (pager: number = 1, username: string = "") => {
  tableLoading.value = true;
  let result: userResponseData = await userRequest.user(
    pageNo.value,
    limit.value,
    username,
  );
  if (result.code == 200) {
    total.value = result.data.total;
    userList.value = result.data.records;
  }
  keyword.value = "";
  pageNo.value = pager;
  tableLoading.value = false;
};

//添加用户按钮点击
const addUser = () => {
  // 先清空上一次数据
  Object.assign(
    newUserData,
    JSON.parse(
      JSON.stringify({
        name: "",
        password: "",
        username: "",
      }),
    ),
  );
  delete newUserData.id;
  // 清除上一次校验信息
  nextTick(() => {
    // 第一次组件挂载还是没有表单，因此在第二次挂载中清除
    nextTick(() => {
      newUserDataForm.value.clearValidate("username");
      newUserDataForm.value.clearValidate("name");
      newUserDataForm.value.clearValidate("password");
    });
  });
  addUserDrawer.value = true;
};

//编辑用户
const updateUser = (row: userObj) => {
  addUserDrawer.value = true;
  newUserData.id = row.id;
  newUserData.username = row.username;
  newUserData.name = row.name;
  newUserData.password = row.password;
};

//提交添加或更新用户
const submitAddUser = async () => {
  if (newUserData.id) {
    //有id，更新用户
    await newUserDataForm.value.validate();
    let result = await userRequest.update(newUserData);
    addUserDrawer.value = false;
    checkResult(result, "更新用户", "code", 200, getUserList);
    // 更新用户信息直接刷新浏览器，因为如果用户修改当前用户，需要让其重新登陆
    window.location.reload();
  } else {
    //无id，添加用户
    await newUserDataForm.value.validate();
    let result = await userRequest.save(newUserData);
    addUserDrawer.value = false;
    checkResult(result, "添加用户", "code", 200, getUserList);
  }
};

//删除用户
const deleteUser = async (id: number) => {
  let result = await userRequest.remove(id);
  checkResult(result, "删除用户", "code", 200, getUserList);
  window.location.reload();
};
//批量删除用户
const deleteUserArr = async () => {
  //处理数据成接口所需格式
  let userSelecedIdArr = userSelecedArr.value.map((item) => item.id); //表示将该数组中所有元素全部转为元素的id
  let result = await userRequest.batchRemove(userSelecedIdArr);
  checkResult(result, "批量删除用户", "code", 200, getUserList);
  window.location.reload();
};

//当多选框改变
const handleSelectionChange = (val: any) => {
  userSelecedArr.value = val;
};

onMounted(() => {
  getUserList();
});

//分配用户角色抽屉控制
const updateUserRole = async (row: any) => {
  Object.assign(newUserData, row);
  let result = await userRequest.toAssign(newUserData.id as number);
  if (result.code == 200) {
    allRole.value = result.data.allRolesList;
    userRole.value = result.data.assignRoles;
    userRoleDrawer.value = true;
  }
};

//用户角色复选框相关样式控制
const handleCheckAllChange = (val: any) => {
  userRole.value = val ? allRole.value : [];
  isIndeterminate.value = false;
};
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === allRole.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length;
};

//提交用户角色
const submitUserRole = async () => {
  //将角色数据整理成后端所需要的格式
  let roleIdList = userRole.value.map((item) => item.id);
  let result = await userRequest.doAssignRole(roleIdList, newUserData.id);
  userRoleDrawer.value = false;
  checkResult(result, "角色分配", "code", 200, getUserList);
};
</script>

<style scoped lang="scss">
.searchForm {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
